/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.vehicle.modular.vehicleinfo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.context.constant.ConstantContextHolder;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.facedoor.modular.memberuser.entity.MemberUser;
import vip.xiaonuo.facedoor.modular.memberuser.mapper.MemberUserMapper;
import vip.xiaonuo.facedoor.modular.message.SnowyMessageTemplate;
import vip.xiaonuo.facedoor.modular.message.Topic;
import vip.xiaonuo.facedoor.modular.message.domain.Message;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.mapper.SysOrgMapper;
import vip.xiaonuo.vehicle.common.domain.ExcelResult;
import vip.xiaonuo.vehicle.modular.vehicleblacklist.entity.VehicleBlacklist;
import vip.xiaonuo.vehicle.modular.vehicleinfo.entity.VehicleInfo;
import vip.xiaonuo.vehicle.modular.vehicleinfo.entity.dto.VehicleInfoDto;
import vip.xiaonuo.vehicle.modular.vehicleinfo.enums.VehicleInfoExceptionEnum;
import vip.xiaonuo.vehicle.modular.vehicleinfo.mapper.VehicleInfoMapper;
import vip.xiaonuo.vehicle.modular.vehicleinfo.param.VehicleInfoParam;
import vip.xiaonuo.vehicle.modular.vehicleinfo.service.VehicleInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.LongAdder;

/**
 * 车辆信息service接口实现类
 *
 * @author cad
 * @date 2023-03-22 17:24:21
 */
@Service
public class VehicleInfoServiceImpl extends ServiceImpl<VehicleInfoMapper, VehicleInfo> implements VehicleInfoService {
    @Resource
    private VehicleInfoMapper vehicleInfoMapper;
    @Resource
    private SysOrgMapper sysOrgMapper;
    @Resource
    private MemberUserMapper memberUserMapper;

    @Resource
    private SnowyMessageTemplate snowyMessageTemplate;

    @Override
    public PageResult<VehicleInfo> page(VehicleInfoParam vehicleInfoParam) {
        QueryWrapper<VehicleInfo> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(vehicleInfoParam)) {

            // 根据车牌号 查询
            if (ObjectUtil.isNotEmpty(vehicleInfoParam.getLicensePlateNumber())) {
                queryWrapper.lambda().eq(VehicleInfo::getLicensePlateNumber, vehicleInfoParam.getLicensePlateNumber());
            }
            // 根据部门id 查询
            if (ObjectUtil.isNotEmpty(vehicleInfoParam.getDeptId())) {
                queryWrapper.lambda().eq(VehicleInfo::getDeptId, vehicleInfoParam.getDeptId());
            }
            // 根据部门名字 查询
            if (ObjectUtil.isNotEmpty(vehicleInfoParam.getDeptName())) {
                queryWrapper.lambda().eq(VehicleInfo::getDeptName, vehicleInfoParam.getDeptName());
            }
            // 根据车辆颜色 查询
            if (ObjectUtil.isNotEmpty(vehicleInfoParam.getVehicleColor())) {
                queryWrapper.lambda().eq(VehicleInfo::getVehicleColor, vehicleInfoParam.getVehicleColor());
            }
            // 根据绑定人员id 查询
            if (ObjectUtil.isNotEmpty(vehicleInfoParam.getPersonnelId())) {
                queryWrapper.lambda().eq(VehicleInfo::getPersonnelId, vehicleInfoParam.getPersonnelId());
            }
            // 根据绑定人员名字 查询
            if (ObjectUtil.isNotEmpty(vehicleInfoParam.getPersonnelName())) {
                queryWrapper.lambda().eq(VehicleInfo::getPersonnelName, vehicleInfoParam.getPersonnelName());
            }
            // 根据联系电话 查询
            if (ObjectUtil.isNotEmpty(vehicleInfoParam.getPhone())) {
                queryWrapper.lambda().eq(VehicleInfo::getPhone, vehicleInfoParam.getPhone());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<VehicleInfo> list(VehicleInfoParam vehicleInfoParam) {
        return this.list();
    }

    @Override
    public void add(VehicleInfoParam vehicleInfoParam) {
        VehicleInfo vehicleInfo1 = vehicleInfoMapper.selectOne(new LambdaQueryWrapper<VehicleInfo>()
                .eq(VehicleInfo::getLicensePlateNumber, vehicleInfoParam.getLicensePlateNumber()));
        if (ObjectUtils.isNotEmpty(vehicleInfo1)){
            throw new ServiceException(500,"已存在该车牌！");
        }
        VehicleInfo vehicleInfo = new VehicleInfo();
        BeanUtil.copyProperties(vehicleInfoParam, vehicleInfo);
        this.save(vehicleInfo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(VehicleInfoParam vehicleInfoParam) {
        this.removeById(vehicleInfoParam.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(VehicleInfoParam vehicleInfoParam) {
        VehicleInfo byId = this.getById(vehicleInfoParam.getId());
        if (!byId.getLicensePlateNumber().equals(vehicleInfoParam.getLicensePlateNumber())){
            VehicleInfo vehicleInfo1 = vehicleInfoMapper.selectOne(new LambdaQueryWrapper<VehicleInfo>()
                    .eq(VehicleInfo::getLicensePlateNumber, vehicleInfoParam.getLicensePlateNumber()));
            if (ObjectUtils.isNotEmpty(vehicleInfo1)){
                throw new ServiceException(500,"已存在该车牌！");
            }
        }
        VehicleInfo vehicleInfo = this.queryVehicleInfo(vehicleInfoParam);
        BeanUtil.copyProperties(vehicleInfoParam, vehicleInfo);
        this.updateById(vehicleInfo);
    }

    @Override
    public VehicleInfo detail(VehicleInfoParam vehicleInfoParam) {
        return this.queryVehicleInfo(vehicleInfoParam);
    }

    @Override
    public void export(VehicleInfoParam vehicleInfoParam) {
        List<VehicleInfo> list = this.list(vehicleInfoParam);
        PoiUtil.exportExcelWithStream("车辆信息.xls",VehicleInfo.class,list);
    }

    @Override
    public ResponseData importData(MultipartFile file) {
        List<VehicleInfoDto> vehicleInfos = PoiUtil.importExcel(file, 0, 1, VehicleInfoDto.class);
        if (CollectionUtils.isEmpty(vehicleInfos)){
            throw new ServiceException(500,"没有有效的数据！");
        }
        LongAdder successLongAdder = new LongAdder();
        LongAdder failLongAdder = new LongAdder();
        ExcelResult excelResult = new ExcelResult();
        List<ExcelResult.FailMessage> failMessageList = new ArrayList<>();
        for (VehicleInfoDto vehicleInfoDto : vehicleInfos) {
            ExcelResult.FailMessage failMessage = new ExcelResult.FailMessage()
                    .setFlag("车牌号").setName(Optional.of(vehicleInfoDto.getLicensePlateNumber()).orElse("标识字段为空"));
            checkAndSave(vehicleInfoDto,successLongAdder,failLongAdder, failMessage);
            failMessageList.add(failMessage);
        }
        excelResult.setSuccessNum(successLongAdder.intValue())
                .setFailNum(failLongAdder.intValue())
                .setFailMessageList(failMessageList);
        return ResponseData.success(excelResult);
    }

    private void checkAndSave(VehicleInfoDto vehicleInfoDto, LongAdder successLongAdder, LongAdder failLongAdder, ExcelResult.FailMessage failMessage) {
        if (StringUtils.isEmpty(vehicleInfoDto.getLicensePlateNumber())){
            failMessage.setFailMessage("车牌号不能为空！");
            failLongAdder.increment();
            return;
        }
        if (StringUtils.isEmpty(vehicleInfoDto.getDeptCode())){
            failMessage.setFailMessage("部门Code不能为空！");
            failLongAdder.increment();
            return;
        }
        SysOrg org = sysOrgMapper.selectOne(new LambdaQueryWrapper<SysOrg>().eq(SysOrg::getCode, vehicleInfoDto.getDeptCode()));
        if (ObjectUtils.isEmpty(org)){
            failMessage.setFailMessage("部门Code错误,找不到部门！");
            failLongAdder.increment();
            return;
        }
        vehicleInfoDto.setDeptId(org.getId());
        vehicleInfoDto.setDeptName(org.getName());
        if (StringUtils.isEmpty(vehicleInfoDto.getPersonnelName())){
            failMessage.setFailMessage("绑定人员名字不能为空！");
            failLongAdder.increment();
            return;
        }

        VehicleInfo vehicleInfo1 = vehicleInfoMapper.selectOne(new LambdaQueryWrapper<VehicleInfo>()
                .eq(VehicleInfo::getLicensePlateNumber, vehicleInfoDto.getLicensePlateNumber()));
        if (ObjectUtils.isNotEmpty(vehicleInfo1)){
            throw new ServiceException(500,"已存在该车牌！");
        }
        List<MemberUser> memberUsers = memberUserMapper.selectList(new LambdaQueryWrapper<MemberUser>()
                .eq(MemberUser::getOrgId, org.getId())
                .eq(MemberUser::getName, vehicleInfoDto.getPersonnelName()));
        if (CollectionUtils.isEmpty(memberUsers)){
            failMessage.setFailMessage("该人员名字找不到！");
            failLongAdder.increment();
            return;
        }
        vehicleInfoDto.setPersonnelId(memberUsers.get(0).getId());
        if (StringUtils.isEmpty(vehicleInfoDto.getPhone())){
            failMessage.setFailMessage("联系方式不能为空！");
            failLongAdder.increment();
            return;
        }
        saveBean(vehicleInfoDto,successLongAdder,failLongAdder,failMessage);
    }

    private void saveBean(VehicleInfoDto vehicleInfoDto, LongAdder successLongAdder, LongAdder failLongAdder, ExcelResult.FailMessage failMessage) {
        VehicleInfoService vehicleInfoService = (VehicleInfoService) AopContext.currentProxy();
        VehicleInfoParam vehicleInfoParam = new VehicleInfoParam();
        try {
            BeanUtils.copyProperties(vehicleInfoDto,vehicleInfoParam);
            vehicleInfoService.add(vehicleInfoParam);
            successLongAdder.increment();
        } catch (BeansException e) {
            failLongAdder.increment();
            failMessage.setFailMessage(e.getMessage());
        }
    }

    /**
     * 获取车辆信息
     *
     * @author cad
     * @date 2023-03-22 17:24:21
     */
    private VehicleInfo queryVehicleInfo(VehicleInfoParam vehicleInfoParam) {
        VehicleInfo vehicleInfo = this.getById(vehicleInfoParam.getId());
        if (ObjectUtil.isNull(vehicleInfo)) {
            throw new ServiceException(VehicleInfoExceptionEnum.NOT_EXIST);
        }
        return vehicleInfo;
    }
}
